/*
 * @Description:  init的操作函数
 * @Author: 听风
 * @Date: 2020-12-24 16:29:35
 */
const Handlebars = require('handlebars');
const Ora = require('ora');
const Inquirer = require('inquirer');
const chalk = require('chalk');
const symbols = require('log-symbols');
const { runExec } = require('../uitls/comd');
const depends = require('../configs/eggDepends');
const {
  downloadGitTemp,
  readFileFromRoot,
  writeFileOnRoot,
  renameFileOnRoot,
  existsSync,
  appendFileOnRoot,
} = require('../uitls/fs');

/**
 * @description: 询问数据库名和启动端口
 * @param {*} async
 * @return {*}
 */
const eggInquirer = async () => {
  const answers = await Inquirer.prompt([
    {
      type: 'input',
      name: 'db',
      message: '请输入mongodb数据库名',
      default: 'db',
    },
    {
      type: 'input',
      name: 'port',
      message: '请输入启动端口',
      default: '7000',
    },
  ]);

  // 渲染模板
  return JSON.parse(Handlebars.compile(JSON.stringify(depends))(answers));
};

/**
 * @description:  初始化egg项目
 * @param {*}
 * @return {*}
 */
// const eggInit = async () => {
//   await runExec('npm init egg --type=simple');
// };

/**
 * @description: egg下载依赖
 * @param {*}
 * @return {*}
 */
const eggDownloadDepends = async depends => {
  let npmStr = 'npm install ';
  for (const { npm, name } of depends) {
    if (npm) {
      npmStr += `${name} `;
    }
  }
  npmStr += '--registry=https://registry.npm.taobao.org/';
  await runExec(npmStr);
};

/**
 * @description: 插入egg config
 * @param {*} tfOptions
 * @return {*}
 */
const importEggConfig = async tfOptions => {
  const defautlConfigFile = 'config/config.default.js';
  if (!existsSync(defautlConfigFile)) {
    return;
  }

  // 在default配置中加入require专属配置
  const configContent = await readFileFromRoot(defautlConfigFile);
  if (!configContent.includes("require('./tf.config')")) {
    const configLines = configContent.split(/\r\n|\n|\r/gm).reverse();
    let index = -1,
      preSpace = '';
    for (index in configLines) {
      if (configLines[index].includes('return')) {
        preSpace = configLines[index - 1].split(/\S/)[0];
        break;
      }
    }
    configLines.splice(index - 2, 0, `${preSpace}...require('./tf.config')`);
    await writeFileOnRoot(defautlConfigFile, configLines.reverse().join('\r\n'));
  }

  // 创建专属配置文件tf.config
  const configPath = 'config';
  const tfConfigFile = 'config/tf.config.js';
  if (!existsSync(tfConfigFile, false)) {
    // 文件不存在则载入
    await downloadGitTemp('egg-config', configPath);
    await renameFileOnRoot(`${configPath}/_egg_config.js`, tfConfigFile);
  }

  // 修改专属配置文件tf.config, 插入配置
  tfOptions.forEach(({ config }) => {
    appendFileOnRoot(tfConfigFile, config);
  });
};

/**
 * @description: 插入plugin
 * @param {*} tfOptions
 * @return {*}
 */
const importEggPlugin = async depends => {
  const pluginFile = 'config/plugin.js';
  if (!existsSync(pluginFile)) {
    return;
  }
  const pluginContent = (await readFileFromRoot(pluginFile))
    .replace(/^'use strict'.*/, '')
    .replace('module.exports', 'prePlugins');
  let plugins = null;
  eval(`${pluginContent};plugins = prePlugins`);
  depends.forEach(({ plugin }) => {
    plugins[plugin[0]] = plugin[1];
  });
  const content = `'use strict';

module.exports = ${JSON.stringify(plugins)}
  `;
  await writeFileOnRoot(pluginFile, content);
};

/**
 * @description: package.json启动的--daemon替换为--no-daemon
 * @param {*}
 * @return {*}
 */
const noDaemonStart = async () => {
  const packageFile = (await readFileFromRoot('package.json')).replace(/--daemon/g, '--no-daemon');
  await writeFileOnRoot('package.json', packageFile);
};

/**
 * @description: 对egg项目的初始化
 * @param {*}
 * @return {*}
 */
const egg = async () => {
  // 先询问是否配置
  // 待补充...

  // 询问数据库名和启动端口
  const tfOptions = await eggInquirer();

  const spinner = Ora('初始化项目中...\n\r').start();
  /**
   * 初始化egg
   */
  // await eggInit();
  console.log(symbols.success, chalk.green('初始化完成'));
  spinner.text = '正在下载依赖...\n\r';

  /**
   * 下载依赖
   */
  if (!existsSync('node_modules')) {
    await runExec('npm install --registry=https://registry.npm.taobao.org/');
  }
  await eggDownloadDepends(depends);
  console.log(symbols.success, chalk.green('依赖下载完成'));
  spinner.text = '正在载入配置...\n\r';
  /**
   * 插入config
   */
  await importEggConfig(tfOptions);

  /**
   * 插入plugin
   */
  await importEggPlugin(depends);

  /**
   * package.json启动的--daemon替换为--no-daemon
   */
  await noDaemonStart();

  console.log(symbols.success, chalk.green('配置载入完成'));
  spinner.succeed('egg项目初始化配置完成\n\r');
};

module.exports = {
  egg,
};
